package com.travelsmart.server.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class UtilDate {
	
	private static String DATE_FORMAT = "MM/dd/yyyy";
	private static SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy");
	
	
	/**
	 * formats the calendar in MM / dd / yyyy
	 * @param calendar
	 * @return
	 */
    public static String formatDate(XMLGregorianCalendar calendar){
    	assert calendar != null;
    	String retorno = sdf.format(calendar.toGregorianCalendar().getTime());	
    	return retorno;
    }
    
    /**
     * 
     * @param date
     * @return String dd-MM-yyyy
     */
    public static String formatDate2(Date date){
    	assert date != null;
    	String retorno = sdf2.format(date);
    	return retorno;
    }

    /**
     * dataFormat in dd-MM-yyyy
     * @param dataFormat
     * @return Date
     */
    public static Date getDate2(String dataFormat){
    	assert dataFormat != null;
    	assert dataFormat.matches("\\d\\d-\\d\\d-\\d\\d\\d\\d");
    	Date retorno = null;
		try {
			retorno = sdf2.parse(dataFormat);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return retorno;
    }
    
    public static String formatDate(Date date){
    	assert date != null;
    	String retorno = sdf.format(date);
    	return retorno;
    }
    
    
    public static Date getDate(XMLGregorianCalendar calendar){
    	Date retorno = null;
    	if(calendar != null){
    		retorno = calendar.toGregorianCalendar().getTime();	
    	}
    	return retorno;
    }
    
    public static XMLGregorianCalendar criarGregorianCalendar(Date data){
		assert data != null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(data);
		XMLGregorianCalendar retorno = null;
		try {
			retorno = DatatypeFactory.newInstance()
			.newXMLGregorianCalendar(
					new GregorianCalendar(calendar.get(Calendar.YEAR),
							calendar.get(Calendar.MONTH), calendar
									.get(Calendar.DAY_OF_MONTH)));
		} catch (DatatypeConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retorno;
	}


}
